// 封装飞机票搜索组件
<template>
  <div class="search-form">
    <!-- 头部tab切换 -->
    <el-row type="flex" class="search-tab">
      <span
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleSearchTab(item, index)"
        :class="{ active: index === currenttab }"
      >
        <i :class="item.icon"></i>
        {{ item.name }}
      </span>
    </el-row>
    <!-- 表单填写 -->
    <el-form
      v-if="currenttab === 0"
      class="search-form-content"
      ref="search-form-content"
      label-width="80px"
    >
      <!-- fetch-suggestions 返回输入建议的方法,通过这个方法获取到输入建议 -->
      <!-- select 点击选中建议项时触发，我们应该确认用户的选择，得到两个参数：departCity,departCode -->
      <el-form-item label="出发城市">
        <el-autocomplete
          :fetch-suggestions="queryDepartSearch"
          :trigger-on-focus="false"
          placeholder="请输入出发城市"
          @select="handleDepartSelect"
          v-model="form.departCity"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="到达城市">
        <el-autocomplete
          :fetch-suggestions="queryDestSearch"
          :trigger-on-focus="false"
          placeholder="请输入到达城市"
          @select="handleDestSelect"
          v-model="form.destCity"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="出发时间">
        <el-date-picker
          type="date"
          placeholder="请选择日期"
          style="width: 100%"
          @change="handleDate"
          v-model="form.departDate"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="">
        <el-button
          style="width: 100%"
          type="primary"
          icon="el-icon-search"
          @click="handleSubmit"
        >
          搜索
        </el-button>
      </el-form-item>
      <!-- 调换出发与到达城市 -->
      <div class="reverse">
        <span @click="handleReverse">换</span>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from "moment";
export default {
  data() {
    return {
      tabs: [
        { icon: "iconfont icondancheng", name: "单程" },
        { icon: "iconfont iconshuangxiang", name: "往返" },
      ],
      currenttab: 0,
      // 在html中绑定表单值
      form: {
        departCity: "", // 出发城市
        departCode: "", //出发城市代码
        destCity: "", //到达城市
        destCode: "", //到达城市代码
        departDate: "", // 出发日期
      },
    };
  },
  methods: {
    // 动态获取输入建议
    getsuggestions(value, type, callback) {
      //发送接口请求
      // JiPiao - 实时机票城市：http:127.0.0.1:1337/airs/city
      this.$axios({
        url: "/airs/city",
        params: { name: value },
      }).then((res) => {
        // 声明变量list，来存放改造后的数据
        let list;
        // 如果没有查询到输入建议
        if (res.data.data.length === 0) {
          callback([{ value: "没有对应城市" }]);
          return; //结束运行
        }
        // 后期需要code代码数据来发送请求，所以改改造数据结构
        list = res.data.data.map((v) => {
          return {
            value: v.name,
            code: v.sort,
          };
        });
        // 过滤掉没有code的城市
        list = list.filter((v) => {
          return v.code; // 不为null就返回
        });
        console.log(list); // 输出查询建议列表
        // 让输入建议的第一项默认填充到文本框
        if (type === "depart") {
          this.form.departCity = list[0].value;
          this.form.departCode = list[0].code;
        } else if (type === "dest") {
          this.form.destCity = list[0].value;
          this.form.destCode = list[0].code;
        }
        callback(list); //回调新数据出来
      });
    },
    // 出发城市下拉选择时触发
    handleDepartSelect(item) {
      console.log(item);
      this.form.departCity = item.value;
      this.form.departCode = item.code;
    },
    // 到达城市下拉选择时触发
    handleDestSelect(item) {
      console.log(item); // 输出被选中的城市项
      this.form.destCity = item.value;
      this.form.destCode = item.code;
    },
    // tab切换时触发
    handleSearchTab(item, index) {
      // this.currenttab = index;
      if (index === 1) {
        this.$confirm("目前暂不支持往返，请使用单程选票！", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
        });
      }
    },
    // 出发城市输入框获得焦点时触发
    queryDepartSearch(value, callback) {
      console.log(value);
      // 根据用户的输入查询输入建议
      // JiPiao - 实时机票城市：http:127.0.0.1:1337/airs/city
      this.getsuggestions(value, "depart", callback);
    },
    // 目标城市输入框获得焦点时触发
    queryDestSearch(value, callback) {
      // 根据用户的输入查询输入建议
      this.getsuggestions(value, "dest", callback);
    },
    // 确认选择日期时触发
    handleDate(value) {
      // console.log(moment(value).format("YYYY-MM-DD"));
      // moment():获取当前日期啰
      // format():可以对日期值进行格式化
      this.form.departDate = moment(value).format("YYYY-MM-DD");
    },
    // 提交表单是触发
    handleSubmit() {
      /* 解决用户不输入也能搜索的问题：通过验证判断是否进行页面跳转
       */
      // 1.添加验证规则
      let rules = {
        depart: {
          value: this.form.departCity,
          message: "请选择出发城市",
        },
        dest: {
          value: this.form.destCity,
          message: "请选择到达城市",
        },
        date: {
          value: this.form.departDate,
          message: "请选择出发时间",
        },
      };
      // 2.设置验证是否通过的标记，默认true通过,后期只要有一个错误就为false
      let flag = true;
      // 3.遍历验证规则，Object.keys(rules) >> ['depart','dest','date']
      Object.keys(rules).forEach((v) => {
        // console.log(v);//'depart','dest','date'
        let item = rules[v]; // 根据key取得相应对象
        if (!item.value) {
          flag = false;
          this.$confirm(item.message, "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning",
          });
          // 减少循环
          return;
        }
      });
      if (!flag) {
        return;
      }

      // 清除城市名称中的最后一个字符  市  字
      // console.log(this.form.departCity);
      let a = this.form.departCity;
      this.form.departCity = a.substr(0, a.length - 1);
      // console.log(a);
      let b = this.form.destCity;
      this.form.destCity = b.substr(0, b.length - 1);
      // 将当前搜索记录存储在store
      this.$store.commit("history/setFlightRecord", this.form);
      // 路由跳转，同时传递参数
      this.$router.push({ path: "/air/flights", query: this.form });
    },
    // 触发和目标城市切换时触发
    handleReverse() {
      // 从form对象中获取相应的数据；再分别赋值
      const { departCity, departCode, destCity, destCode } = this.form;
      this.form.departCity = destCity;
      this.form.departCode = destCode;

      this.form.destCity = departCity;
      this.form.destCode = departCode;
    },
  },
};
</script>

<style lang="less" scoped>
.search-form {
  border: 1px solid #ddd;
  border-top: none;
  width: 360px;
  height: 350px;
  box-sizing: border-box;
  .search-tab {
    span {
      display: block;
      flex: 1;
      text-align: center;
      height: 48px;
      line-height: 42px;
      box-sizing: border-box;
      border-top: 3px #eee solid;
      background: #eee;
      cursor: pointer;
    }
    .active {
      border-top: 3px solid orange;
      background: #fff;
    }
  }
  .search-form-content {
    position: relative;
    padding: 15px 50px 15px 15px;
    .el-autocomplete {
      width: 100%;
    }
    .reverse {
      position: absolute;
      top: 35px;
      right: 15px;
      &:after,
      &:before {
        display: block;
        content: "";
        position: absolute;
        left: -35px;
        width: 25px;
        height: 1px;
        background: #ccc;
      }
      &:after {
        top: 60px;
      }
      &:before {
        top: 0;
      }
      span {
        display: block;
        position: absolute;
        top: 20px;
        right: 0;
        font-size: 12px;
        background: #999;
        color: #fff;
        width: 20px;
        height: 20px;
        line-height: 18px;
        text-align: center;
        border-radius: 2px;
        cursor: pointer;

        &:after,
        &:before {
          display: block;
          content: "";
          position: absolute;
          left: 10px;
          width: 1px;
          height: 21px;
          background: #ccc;
        }

        &:after {
          top: -20px;
        }
        &:before {
          top: 20px;
        }
      }
    }
  }
}
</style>